/**
 *author:yhb
 */
package com.towker.frame.controller.sys;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.towker.core.encrypt.EncryptUtil;
import com.towker.core.page.PageModel;
import com.towker.core.page.PageNav;
import com.towker.frame.controller.BaseController;
import com.towker.frame.model.basicData.Companies;
import com.towker.frame.model.basicData.Departments;
import com.towker.frame.model.sys.User;
import com.towker.frame.service.basicData.CompaniesService;
import com.towker.frame.service.basicData.DepartmentsService;
import com.towker.frame.service.rbac.RoleUserService;
import com.towker.frame.service.rbac.role.RoleService;
import com.towker.frame.service.sys.user.UserService;
import com.towker.frame.share.sys.user.UserShare;
import com.towker.web.MyRequest;


@Controller
@RequestMapping("/manage/sys/user")
public class UserController extends BaseController
{
	// 用户管理业务处理对象。
	private UserService service;
	private RoleUserService roleUserService;
	private RoleService roleService;
	private DepartmentsService departmentsService;
	private CompaniesService companiesService;
	
	public void setUserService(UserService service)
	{
		this.service = service;
	}

	public void setRoleUserService(RoleUserService roleUserService)
	{
		this.roleUserService = roleUserService;
	}

	public void setRoleService(RoleService roleService)
	{
		this.roleService = roleService;
	}
	
	public void setDepartmentsService(DepartmentsService departmentsService) {
		this.departmentsService = departmentsService;
	}
	
	//业务对象注入
	public void setCompaniesService(CompaniesService companiesService)
	{
		this.companiesService = companiesService;
	}

	/** 添加用户 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/addUser{viewName}")
	public ModelAndView addUser(HttpServletResponse response, HttpServletRequest request, User po, @PathVariable String viewName) throws Exception
	{
		ModelAndView result = null;
		MyRequest req = new MyRequest(request);
		Map map = null;
		if ("1".equals(viewName))
		{
			result = new ModelAndView();
			Map map2 = new HashMap();
			List departList = departmentsService.getList(map2);//部门信息
			result.addObject("departList", departList);
			List companiesList = companiesService.getList(map2);//公司信息
			result.addObject("companiesList",companiesList);
			Map groupMap = new HashMap();
			groupMap.put("pid", 0);
			List userGroups = service.getList(groupMap);
			result.addObject("userGroups", userGroups);	
			
			result.setViewName("/manage/sys/user/addUser_p.jsp");
		}
		else if ("2".equals(viewName))
		{
			Integer pid = req.getInt("id");
			User user = service.getById((long) pid);
			map = new HashMap();
			result = new ModelAndView();
			result.addObject("user", user);
			
			Map map2 = new HashMap();
			List departList = departmentsService.getList(map2);//部门信息
			result.addObject("departList", departList);
			List companiesList = companiesService.getList(map2);//公司信息
			result.addObject("companiesList",companiesList);
			Map groupMap = new HashMap();
			groupMap.put("pid", 0);
			List userGroups = service.getList(groupMap);
			result.addObject("userGroups", userGroups);	
			result.setViewName("/manage/sys/user/addUser_s.jsp");
		}
		else if ("3".equals(viewName))
		{
			PrintWriter writer = response.getWriter();
			try
			{
				map = new HashMap();
				map.put("name", po.getName());
				System.out.println(po.getusertype());
				List<User> list = service.getList(map);
				if (list.size() > 0)
				{
					writer.write("您所要添加的用户组名称已存在！");
					return result;
				}
				service.add(po);
				writer.write("添加用户组成功！");
			}
			catch (Exception e)
			{
				e.printStackTrace();
				writer.write("添加用户组失败!");
			}
		}
		else if ("4".equals(viewName))
		{
			PrintWriter writer = response.getWriter();
			try
			{
//				System.out.println(po.getusertype() + "--" + po.getPid());
				map = new HashMap();
				map.put("account", po.getAccount());
				List<User> list = service.getList(map);
				if (list.size() > 0)
				{
					writer.write("您所要添加的帐号已存在！");
					return result;
				}
				Companies co = companiesService.getByCode(po.getCoCode());
				if (co != null) {
					po.setCoName(co.getCo_name());
					po.setCoId(co.getId());
				}
				po.setStatus(1);
				po.setPassword(EncryptUtil.encryptMd5(po.getPassword()));
				service.add(po);
				//给用户分配角色
//				map.clear();
//				List<Role> roles = null;
//				switch (po.getUsertype())
//				{
//					case 1:
//						map.put("roletype", 1);
//						
//						break;
//					case 2:
//						map.put("roletype", 2);					
//						break;
//					case 3:
//						map.put("roletype", 3);
//						break;
//					case 4:
//						map.put("roletype", 4);
//						break;
//					
//					default:
//						break;
//				}
//				roles = roleService.getList(map);
//				RoleUser roleUser = new RoleUser();
//				roleUser.setSystemid(1L);
//				roleUser.setUserid(po.getId());
//				roleUser.setRoleid(roles.get(0).getId());
//				roleUserService.add(roleUser);   
				writer.write("添加用户信息成功！");
			}
			catch (Exception e)
			{
				e.printStackTrace();
				writer.write("添加用户信息失败!");
			}
		}
		return result;
	}

	/** 批量删除用户 */
	@RequestMapping("delUser{viewName}")
	public void delByUserIds(HttpServletRequest request, HttpServletResponse response, @PathVariable String viewName) throws Exception
	{
		PrintWriter out = response.getWriter();
		MyRequest req = new MyRequest(request);
		if ("1".equals(viewName))
		{
			try
			{
				String id = req.getString("ids");
				String[] ids = id.split(",");
				for(int i=0;i<ids.length;i++)
				{
					service.delById(Long.parseLong(ids[i]));
					roleUserService.delByUserid(Long.parseLong(ids[i]));
				}
				out.write("删除用户成功！");
			}
			catch (Exception e)
			{
				e.printStackTrace();
				out.print("删除用户失败！");
			}
		}
		else if ("2".equals(viewName))
		{
			try
			{
				Long id = req.getLong("id");
				service.delById(id);
				roleUserService.delByUserid(id);
				out.write("删除用户成功！");
			}
			catch (Exception e)
			{
				e.printStackTrace();
				out.print("删除用户失败！");
			}
		}
	}

	// 删除
	@RequestMapping("/delUserTree")
	public void delUserTree(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		// out.print(1)-成功，out.print(2)-有下级不能删。
		PrintWriter out = response.getWriter();
		try
		{
			MyRequest req = new MyRequest(request);
			long id = req.getLong("id", 0);
			int count = service.getCount(id);
			if (0 == count)
			{
				service.delById(id);
				out.print(1);
			}
			else
			{
				out.print(2);
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
			out.print("0:" + e.getMessage());
		}
	}

	/** 根据用户编号重新设置密码信息 */
	@RequestMapping("/resetPwd{viewName}")
	public ModelAndView resetPwd(HttpServletRequest request, HttpServletResponse response, User po, @PathVariable String viewName) throws IOException, Exception
	{
		ModelAndView result = null;
		MyRequest req = new MyRequest(request);
		long userId = req.getLong("id");
		if ("1".equals(viewName))
		{
			User user = service.getById(userId);
			result = new ModelAndView();
			result.addObject("id", user.getId());
			result.setViewName("/manage/sys/user/resetPwd.jsp");
		}
		else if ("2".equals(viewName))
		{
			PrintWriter writer = response.getWriter();
			try
			{
				service.resetPwd(userId, req.getString("password"));
				writer.write("密码重置成功！");
			}
			catch (Exception e)
			{
				e.printStackTrace();
				writer.write("密码重置失败！");
			}
		}
		return result;
	}

	/** 更新用户信息 除了像密码修改，还有账号修改之外的信息 */
	@RequestMapping("/updUser{viewName}")
	public ModelAndView updUser(HttpServletRequest request, HttpServletResponse response, User po, @PathVariable String viewName) throws IOException, Exception
	{
		ModelAndView result = null;
		if ("1".equals(viewName))
		{
			MyRequest req = new MyRequest(request);
			User user = service.getById(req.getLong("keyIndex"));
			result = new ModelAndView();
			result.addObject("user", user);
			Map map2 = new HashMap();
			Map groupMap = new HashMap();
			groupMap.put("pid", 0);
			List userGroups = service.getList(groupMap);
			List departList = departmentsService.getList(map2);//部门信息
			result.addObject("departList", departList);
			List companiesList = companiesService.getList(map2);
			result.addObject("companiesList",companiesList);
			result.addObject("userGroups", userGroups);			
			result.setViewName("manage/sys/user/updUser.jsp");
		}
		else if ("2".equals(viewName))
		{
			PrintWriter writer = response.getWriter();
			try
			{
				int userType = -1;
				if (po.getUserStatus() == 1) {
					po.setPid(27834);
					userType = -1;
				} else if (po.getPid() > 0) {
					User group = service.getById(po.getPid());
					userType = group.getUsertype();
				}
				po.setUsertype(userType);
				User user = service.getById(po.getId());
				if (!user.getPassword().equals(po.getPassword()))
				{
					po.setPassword(EncryptUtil.encryptMd5(po.getPassword()));
				} else {
					po.setPassword(user.getPassword());
				}
				Companies co = companiesService.getByCode(po.getCoCode());
				if (co != null) {
					po.setCoName(co.getCo_name());
					po.setCoId(co.getId());
				}
				//service.updateUser(po.getAccount(), po.getPassword(), po.getName(), po.getId());
				service.update(po);
				writer.write("修改用户信息成功！");
			}
			catch (Exception e)
			{
				e.printStackTrace();
				writer.write("修改用户信息失败！");
			}
		}
		else if ("3".equals(viewName))
		{
			PrintWriter writer = response.getWriter();
			try
			{
				service.update(po);
				// UserShare.setUserLogined(request, response, po);
				writer.write("修改成功！");
			}
			catch (Exception e)
			{
				e.printStackTrace();
				writer.write("修改失败！");
			}
		}
		return result;
	}

	/** 获得所有用户json数组 */
	@RequestMapping("/getAllUser")
	public void getAllUser(HttpServletResponse response) throws IOException
	{
		PrintWriter writer = response.getWriter();
		String str = service.getAllUser();
		writer.write(str);
	}

	/** 根据角色ID获得已分配部门的用户 */
	@RequestMapping("/getAssignedUserByRoleid")
	public void getAssignedUserByRoleid(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		PrintWriter writer = response.getWriter();
		String str = service.getAssigendUserByRoleid(new Long(new MyRequest(request).getString("roleid")));
		writer.write(str);
	}

	@RequestMapping("/getAssignedUserByUserid")
	public void getAssignedUserByUserid(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		PrintWriter writer = response.getWriter();
		String str = service.getAssignedUserByUserid(new Long(new MyRequest(request).getString("userid")));
		writer.write(str);
	}

	/** 获得用户分页视图 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/getUser")
	public ModelAndView getUser(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "page", defaultValue = "1") int page) throws IOException
	{
		MyRequest req = new MyRequest(request);
		Map map = req.getParameterValueMap(false, true);
		PageModel<User> pageModel = service.getUserPage(page, map);
		PageNav pageNav = new PageNav(request, pageModel);
		ModelAndView result = new ModelAndView();
		result.addObject("pageModel", pageModel);
		result.addObject("pageNav", pageNav);
		result.setViewName("/manage/sys/user/getUser.jsp");
		return result;
	}

	/** 获得用户分页视图 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/getDiffUser")
	public ModelAndView getDiffUser(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "page", defaultValue = "1") int page) throws IOException
	{
		MyRequest req = new MyRequest(request);
		long sid = req.getLong("pid");
		User user = service.getById(sid);
		Map map = req.getParameterValueMap(false, true);
		map.put("usertype", user.getUsertype());
		PageModel<User> pageModel = service.getPage(page, 10, map);
		PageNav pageNav = new PageNav(request, pageModel);
		ModelAndView result = new ModelAndView();
		result.addObject("pageModel", pageModel);
		result.addObject("pageNav", pageNav);
		result.addObject("user", user);
		result.addObject("id", user.getId());
		result.setViewName("/manage/sys/user/getUser.jsp");
		return result;
	}

	/** 查看用户信息 */
	@RequestMapping("/getUserById")
	public ModelAndView getUserById(HttpServletRequest request, HttpServletResponse response)
	{
		MyRequest req = new MyRequest(request);
		long keyIndex = req.getLong("keyIndex");
		User user = service.getById(keyIndex);
		ModelAndView result = new ModelAndView();
		result.addObject("user", user);
		result.setViewName("/manage/sys/user/getUserById.jsp");
		return result;
	}

	/** 获得用户json数据 */
	@RequestMapping("/getUserJson")
	public void getUserJson(HttpServletResponse response) throws IOException
	{
		PrintWriter writer = response.getWriter();
		String str = service.getUserJson();
		writer.write(str);
	}

	/** 查找提案委用户信息 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/getKzById")
	public ModelAndView getKzById(HttpServletRequest request, HttpServletResponse response)
	{
		ModelAndView result = new ModelAndView();
		Map map = new HashMap();
		map.put("usertype", 2);
		map.put("status", 1);
		List<User> user = service.getList(map);
		result.addObject("user", user.get(0));
		result.setViewName("/manage/sys/user/updKz.jsp");
		return result;
	}

	/** 获得用户分页视图 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/getUserTree")
	public ModelAndView getUserTree(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "page", defaultValue = "1") int page) throws IOException
	{
		MyRequest req = new MyRequest(request);
		Map map = req.getParameterValueMap(false, true);
		PageModel<User> pageModel = service.getUserPage(page, map);
		PageNav pageNav = new PageNav(request, pageModel);
		ModelAndView result = new ModelAndView();
		result.addObject("pageModel", pageModel);
		result.addObject("pageNav", pageNav);
		result.setViewName("/manage/sys/user/getUserTree.jsp");
		return result;
	}

	// getUserByPid
	@SuppressWarnings("unchecked")
	@RequestMapping("/getUserByPid")
	public void getUserByPid(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		PrintWriter out = response.getWriter();
		Map m = new HashMap();
		MyRequest req = new MyRequest(request);
		long pid = req.getLong("pid");
		m.put("pid", pid);
		m.put("status", 0);
		out.print(service.getList(m));
	}
	@RequestMapping("/reg{viewName}")
	public ModelAndView regUser(HttpServletRequest request, HttpServletResponse response, User po, @PathVariable String viewName) throws IOException {
		ModelAndView result =null;
		PrintWriter writer = response.getWriter();
		if ("2".equals(viewName)) {
			Map map = new HashMap();
			map.put("account", po.getAccount());
			List<User> list = service.getList(map);
			if (list.size() > 0)
			{
				writer.write("您注册的用户名已存在,  请填写其他用户名");
				return result;
			} else {
				po.setPid(27834);
				po.setUserStatus(1);
				po.setusertype(-1);
				service.add(po);
				writer.write("用户申请成功,请等待审核！");
			}				
		} else {
			result = new ModelAndView();
			result.setViewName("/manage/sys/user/reg.jsp");
		}
		return result;
	}
	
	@RequestMapping("/myInfo{viewName}")
	public ModelAndView myInfo(HttpServletRequest request, HttpServletResponse response, User po, @PathVariable String viewName) throws IOException {
		ModelAndView result =null;
		PrintWriter writer = response.getWriter();
		if ("2".equals(viewName)) {
			MyRequest req = new MyRequest(request);
			User user = service.getById(UserShare.getCurrentUserId(request));
			user.setDateOfBirth(req.getDate("dateOfBirth"));
			user.setName(req.getString("name"));
			user.setPhone(req.getString("phone"));
			user.setRealname(req.getString("realname"));
			user.setDuty(req.getString("duty"));
			user.setEmail(req.getString("email"));
			user.setFax(req.getString("fax"));
			user.setMobile(req.getString("mobile"));
			user.setGender(req.getInt("gender"));
			String password = req.getString("password");
			try {
				if (!user.getPassword().equals(password)) {
					user.setPassword(EncryptUtil.encryptMd5(password));
				} else {
					user.setPassword(user.getPassword());
				}

				service.update(user);
				writer.write("修改个人信息成功！");
			} catch (Exception e) {
				e.printStackTrace();
				writer.write("修改个人信息失败！");
			}
			
		} else {
			User user = service.getById(UserShare.getCurrentUserId(request));
			Departments dep = departmentsService.getByCode(user.getDeptCode());
			Companies companies = companiesService.getByCode(user.getCoCode());
			result = new ModelAndView();
			result.addObject("user", user);
			result.addObject("dep_name", dep == null ? "" : dep.getDep_name());
			result.addObject("co_name", companies == null ? "" : companies.getCo_name());
			result.setViewName("/manage/sys/user/myInfo.jsp");
		}
		return result;
	}
}
